<template>
  <div class="home">
    userid: <input type="text" v-model="userid">
    昵称：<input type="text" v-model="name">
    消息：<input type="text" v-model="msg" />
    <button @click="send">发送</button>
    <button @click="join">连接</button>
    <button @click="sendmsg">发送给指定的人</button>

    <ul>
      <li v-for="(item,index) in chatList" :key="item.name + index">
        {{ item.name }}说：{{ item.msg }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "Chat_room",
  data() {
    return {
      users: [],
      msg: "",
      chatList: [],
      name: '',
      userid: ''
    };
  },
  sockets: {
    // 连接后台socket
    connect() {
      console.log('socket connected');
    },
    // 用户后台调用，添加数据
    sendMessage(data) {
      console.log(data);
      this.chatList.push(data)
    },
    // 用户后台调用，打印数据
    receivemsg(data) {
      console.log('receivemsg');
      console.log(data);
    }
  },
  methods: {
    // 发送消息给后台
    send() {
      // 使用emit调用后台的socket中的message方法
      this.$socket.emit("message", {
        userid: 100,
        name: this.name,
        msg: this.msg
      });
    },
    // 建立用户连接
    join() {
      this.$socket.emit("join", {
        userid: this.userid
      });
    },
    // 发送消息给后台 用于私发消息
    sendmsg() {
      this.$socket.emit("sendmsg", {
        userid: this.userid,
        msg: this.msg
      });
    }
  }
};
</script>

<style scoped>

</style>